import { useAppStoreWithOut } from '@/store';
import { Router } from 'vue-router';

export function setupRouterGuard(router: Router) {
	createProcessGuard(router);
}

/**
 * 创建进程守卫
 *
 * @param {Router} router
 */
function createProcessGuard(router: Router) {
	router.beforeEach((to: any, from: any, next: any) => {
		// 当前视图统一资源存在 并且 访问用户模式为 登录用户且拥有指定资源能力(4)
		if (to.meta.accessKey && to.meta.accUserMode === 4) {
			// 统一资源
			const unires = App.getAppData()?.unires;
			if (!unires) {
				next({ path: '/401' });
				return;
			}
			const index = unires.findIndex((key: any) => {
				return key === to.meta.accessKey;
			});
			if (index === -1) {
				next({ path: '/401' });
				return;
			}
		}
		if (sessionStorage.getItem('lockState') && to.path != '/lock') {
			next({ path: '/lock' });
		} else {
			if (
				to.meta &&
				!to.meta.ignoreAddPage &&
				to.meta.tag !== 'AppWFRedirectView'
			) {
				const { addPage } = useAppStoreWithOut();
				addPage(to);
			}
			next();
		}
	});
}
